package cn.wolfcode.luowowo.webSite.interceptor;

import cn.wolfcode.luowowo.cache.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.webSite.annotation.RequireLogin;
import cn.wolfcode.luowowo.webSite.util.CookieUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * jdk1.8之后  HandlerInterceptor接口拥有新特性,接口方法定义时会默认实现,我们只需要重写我们需要用到的方法即可
 *  所以我们定义拦截器只需要实现HandlerInterceptor接口就行,不再需要实现HandlerInterceptorAdapter适配器类了
 * */
public class CheckLoginInterceptor implements HandlerInterceptor {

    @Reference
    private IUserInfoRedisService redisService;

    //检查用户是否已登录
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //springmvc启动时将所有映射方法都封装成handler对象
        if(handler instanceof HandlerMethod){
            //只有动态请求才可以强转
            HandlerMethod h = (HandlerMethod)handler;
            //判断该方法上是否有贴@RequireLogin注解
            if(h.hasMethodAnnotation(RequireLogin.class)){
                //如果有的话进行登录检查
                String token = CookieUtil.getToken(request);

                UserInfo userInfo = redisService.getUserByToken(token);
                if(userInfo==null){
                    response.sendRedirect("/login.html");
                    return  false;
                }
            }
        }
        //没有贴@RequireLogin注解的话直接放行
        return true;
    }
}
